package com.gykfbxxh.imovie.utils.glide;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.LruCache;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.utils.NetUtils;

import jp.wasabeef.glide.transformations.BlurTransformation;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

/**
 * Created by gc on 2017/9/9.
 * Net
 */
public class ImageLoader {


    private static ImageLoader mInstance;
    /**
     * 图片缓存核心对象
     */
    private LruCache<String, Bitmap> mLruCache;
    private RequestOptions options;

    private ImageLoader() {
        init();
    }

    public static ImageLoader getInstance() {
        if (mInstance == null) {
            synchronized (ImageLoader.class) {
                if (mInstance == null) {
                    mInstance = new ImageLoader();
                }
            }
        }
        return mInstance;
    }


    /**
     *
     */
    private void init() {
        /**
         * 应用最大内存
         */
//        long maxMemory = Runtime.getRuntime().maxMemory();
//        int cacheMemory = (int) (maxMemory / 8);
//        mLruCache = new LruCache<String, Bitmap>(cacheMemory){
//            @Override
//            protected int sizeOf(String key, Bitmap value) {
//                //每一行占用字节数 *　高度
//                return value.getRowBytes() * value.getHeight();
//            }
//        };

        options = new RequestOptions()
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)  //设置磁盘缓存策略
                .placeholder(R.drawable.loadimg_def_bg)
                .error(R.drawable.loadimg_def_bg)
                .priority(Priority.HIGH);
    }

    /**
     * 加载图片并
     *
     * @param context
     */
    public void loadImage2Cache(final Context context, final ImageView iv, final String path) {
        if (TextUtils.isEmpty(path) || iv == null) {
            return;
        }
        if (checkTag(iv, path)) {
            iv.setTag(R.id.tag_xlistimg, path);
//            Bitmap bitmapFromLocal = LocalCacheUtils.getBitmapFromLocal(path);
//
//            if (bitmapFromLocal != null) {
//                iv.setImageBitmap(bitmapFromLocal);
//                return;
//            }

            if (!NetUtils.isConnected(context)) {
                Glide.with(context).load(R.drawable.loadimg_def_bg).into(iv);
                return;
            }
            Glide.with(context)
                    .asBitmap()
                    .load(path)
                    .listener(new RequestListener<Bitmap>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
//                            LogUtils.e("xuxh", "load请求失败重新请求onException: " + target.getRequest().isRunning());
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
//                            LogUtils.e("xuxh", ":load请求成功onResourceReady succsess");
                            return false;
                        }
                    })
                    .apply(options)
                    .into(iv);
//                    .into(new SimpleTarget<Bitmap>() {
//                        @Override
//                        public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
////                            LocalCacheUtils.setBitmapToLocal(path, bitmap);
//
//                            iv.setImageBitmap(bitmap);
//                        }
//                    });
        }
    }

    /**
     * 加载图片高斯模糊
     *
     * @param context
     */
    public void loadImageTrans2Cache(final Context context, final ImageView iv, final String path) {

        if (!NetUtils.isConnected(context)) {
            Glide.with(context).load(R.drawable.loadimg_def_bg).into(iv);
            return;
        }

        Glide.with(context)
                .asBitmap()
                .load(path)
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
//                        LogUtils.e("xuxh", "loadTrans请求失败重新请求onException: " + target.getRequest().isRunning());
                        loadImageTrans2Cache(context,iv,path);
                        return true;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
//                        LogUtils.e("xuxh", ":loadTrans请求成功onResourceReady succsess");
                        return false;
                    }
                })
                .apply(bitmapTransform(new BlurTransformation(25)))
//                .apply(optionsTrans)
                .into(iv);
//                .into(new SimpleTarget<Bitmap>() {
//                    @Override
//                    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
//                        iv.setImageBitmap(bitmap);
//                    }
//                });
    }


    /**
     * 加载图片并
     *
     * @param context
     */
    public void listLoadImage2Cache(final Context context, final ImageView iv, final String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        if (checkTag(iv, path)) {
            iv.setTag(R.id.tag_xlistimg, path);
//            LogUtils.e("xuxh", "listload_" + path);
//            Bitmap bitmapFromLocal = LocalCacheUtils.getBitmapFromLocal(path);
//            if (bitmapFromLocal != null) {
//                iv.setImageBitmap(bitmapFromLocal);
//                return;
//            }
//
//
            if (!NetUtils.isConnected(context)) {
                Glide.with(context).load(R.drawable.loadimg_def_bg).into(iv);
                return;
            }
            Glide.with(context)
                    .asBitmap()
                    .load(path)
                    .listener(new RequestListener<Bitmap>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
//                            LogUtils.e("xuxh", "listload请求失败重新请求onException: " + target.getRequest().isRunning());
                            loadImage1zhi(context,iv,path);
                            return true;
                        }

                        @Override
                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
//                            LogUtils.e("xuxh", ":listload请求成功onResourceReady succsess");
                            return false;
                        }
                    })
                    .apply(options)
                    .into(iv);
//                    .into(new SimpleTarget<Bitmap>() {
//                        @Override
//                        public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
////                            LocalCacheUtils.setBitmapToLocal(path, bitmap);
//
//                            iv.setImageBitmap(bitmap);
//                        }
//                    });
        }
    }

    /**
     * 不重复加载->防止已加载的图片重复加载,防止闪屏;
     *
     * @param imageView
     * @param url
     * @return 布尔值 false 表示tag一样  true 表示tag不一样
     */
    private boolean checkTag(ImageView imageView, String url) {
        String tagObject = (String) imageView.getTag(R.id.tag_xlistimg);
        if (TextUtils.isEmpty(tagObject)) {
            return true;
        } else if (!TextUtils.isEmpty(url) && tagObject.equals(url)) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 加载图片并
     *
     * @param context
     */
    public void loadSmallImage2Cache(final Context context, final ImageView iv, final String path) {
        if (checkTag(iv, path)) {
            iv.setTag(R.id.tag_xlistimg, path);
            RequestOptions smallOptions = new RequestOptions()
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)  //设置磁盘缓存策略
                    .priority(Priority.HIGH);
//
//            Bitmap bitmapFromLocal = LocalCacheUtils.getBitmapFromLocal(path);
//            if (bitmapFromLocal != null) {
//                iv.setImageBitmap(bitmapFromLocal);
//                return;
//            }

            Glide.with(context)
                    .asBitmap()
                    .load(path)
                    .listener(new RequestListener<Bitmap>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
//                            LogUtils.e("xuxh", ":loadSmall请求成功onResourceReady succsess");
                            return false;
                        }
                    })
                    .apply(smallOptions)
                    .into(iv);
//                    .into(new SimpleTarget<Bitmap>() {
//                        @Override
//                        public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
////                            LocalCacheUtils.setBitmapToLocal(path, bitmap);
//                            iv.setImageBitmap(bitmap);
//                        }
//                    });
        }
    }



    /**
     * 加载图片并
     * @param context
     */
    public void loadImage1zhi(final Context context, final ImageView iv, final String path) {
        if (TextUtils.isEmpty(path) || iv == null) {
            return;
        }
        if (!NetUtils.isConnected(context)) {
            Glide.with(context).load(R.drawable.loadimg_def_bg).into(iv);
            return;
        }
        Glide.with(context)
                .asBitmap()
                .load(path)
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
//                        LogUtils.e("xuxh", "load请求失败重新请求onException: " + target.getRequest().isRunning());
                        loadImage1zhi(context, iv, path);
                        return true;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
//                        LogUtils.e("xuxh", ":load请求成功onResourceReady succsess");
                        return false;
                    }
                })
                .apply(options)
                .into(iv);
    }



}
